package com.liu.controller;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.liu.model.User;
import com.liu.service.UserService;
import com.liu.tools.ActionContextUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by liu on 2018/3/26.
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @PostMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
    public String add(HttpServletRequest req, User user) {
        userService.add(user);
        return "success";
    }

    @ResponseBody
    @PostMapping(value = "/edit", produces = {"application/json;charset=UTF-8"})
    public String edit(HttpServletRequest req, User user) {
        userService.edit(user);
        return "success";
    }


    @RequestMapping(value = "/list", produces = {"application/json;charset=UTF-8"})
    public PageInfo findAllUser(int pageNum, int pageSize) {
        Map<String, Object> queryMap = new HashMap<String, Object>(0);
        String userName = ActionContextUtils.getParameter("userName");
        if (userName != null && !userName.equals("")) {
            queryMap.put("userName", userName);
        }
        List<User> list = userService.findAll(pageNum, pageSize, queryMap);
        return new PageInfo(list);
    }

    @RequestMapping(value = "/detail", produces = {"application/json;charset=UTF-8"})
    public User findUser(String id) {
        User user = userService.findById(id);
        return user;
    }

    @ResponseBody
    @PostMapping(value = "/delete", produces = {"application/json;charset=UTF-8"})
    public String del(String id) {
        userService.deleteById(id);
        return "success";
    }


    @ResponseBody
    @PostMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
    public String login(HttpServletRequest req, User user) {

        User loginUser = userService.login(user);

        Map<String, Object> message = new HashMap<>();

        if (null != loginUser) {
            message.put("status", "success");
            message.put("user", loginUser);
        } else {
            message.put("status", "error");
        }
        return JSON.toJSONString(message);
    }
}